package com.example.content.fragment.personal

import android.graphics.Color
import android.util.Log
import android.view.View
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.example.content.*
import com.example.content.adapter.viewpager.HomePagerAdapter
import com.example.content.databinding.FragmentDetailPersonalBinding
import com.example.content.ext.convertUrl
import com.example.content.fragment.BaseMvvmFragment
import com.example.content.fragment.me.userproduct.UserProductFragment
import com.example.content.manager.GlobalMgr
import com.example.content.manager.ShareMgr
import com.example.content.viewmodule.login.TokenStore
import com.example.content.viewmodule.personal.PersonalViewModel
import com.example.core.utils.DensityUtils
import com.google.android.material.appbar.AppBarLayout
import kotlin.math.abs
import kotlin.math.round

/**
 * Created by zhudongao
 * Desc
 * Date 2020/11/28
 */
class PersonalFragment : BaseMvvmFragment<FragmentDetailPersonalBinding, PersonalViewModel>() {

    var currentColor = Color.WHITE
    private val avatarPoint = FloatArray(2)
    private val spacePoint = FloatArray(2)

    private var verticalHeight = 1f
    private var horizontalWidth = 0

    private var userId: Int = -1
    private var isSelf = false
    private var follow = 0
    private val tabTitles = arrayOf("视频", "美图", "喜欢")
    private val fragments = mutableListOf<Fragment>()
    private lateinit var viewPagerAdapter: HomePagerAdapter

    override fun initView() {
        userId = arguments?.getInt(USER_ID, -1)!!
        isSelf = userId == TokenStore.userId

        val videoPager = UserProductFragment(USER_VIDEO)
        videoPager.userId = userId
        fragments.add(videoPager)
        val photoPager = UserProductFragment(USER_PHOTO)
        photoPager.userId = userId
        fragments.add(photoPager)
        val likePager = UserProductFragment(USER_LIKE)
        likePager.userId = userId
        fragments.add(likePager)

        //初始化tab
        viewPagerAdapter = HomePagerAdapter(childFragmentManager, fragments, tabTitles)
        dataBinding.viewPager.adapter = viewPagerAdapter
        dataBinding.tabLayout.setViewPager(dataBinding.viewPager, tabTitles)
    }

    override fun initListener() {
        dataBinding.personShare.setOnClickListener {
            ShareMgr.openBottom()
        }
        dataBinding.backClick.setOnClickListener {
            activity?.finish()
        }
        dataBinding.followBtn.setOnClickListener {
            viewModel.doFollow(userId, follow)
        }
        dataBinding.followUser.setOnClickListener {
            viewModel.doFollow(userId, follow)
            Log.e("ddddddd", "initListener follow: " + follow)
        }
        dataBinding.appBarLayout.addOnOffsetChangedListener(AppbarLayoutChangeListener())

        viewModel.followersData.observe(this, {
            if (it.isNotEmpty()) {
                val data = it[0]
                Glide.with(this).load(data.avatar.convertUrl()).into(dataBinding.ivHead)
                dataBinding.nickName.text = data.nickname
                dataBinding.signature.text = data.signature
                dataBinding.followNum.text = data.follow_num.toString()
                dataBinding.fansNum.text = data.fans_num.toString()
                dataBinding.likeNum.text = data.liked_num.toString()
                follow = data.follow_related
                Glide.with(this).load(data.avatar.convertUrl()).into(dataBinding.topIcon)
                if (isSelf) {
                    dataBinding.followUser.visibility = View.GONE
                    dataBinding.followBtn.visibility = View.GONE
                } else {
                    dataBinding.followUser.visibility = View.VISIBLE
                    dataBinding.followBtn.visibility = View.VISIBLE
                    doFollow(data.follow_related)
                }
                tabTitles[0] = "视频(${data.user_video_num})"
                tabTitles[1] = "美图(${data.user_photo_num})"
                tabTitles[2] = "喜欢(${data.user_like_num})"
                dataBinding.viewPager.adapter =
                    HomePagerAdapter(childFragmentManager, fragments, tabTitles)
                dataBinding.tabLayout.setViewPager(dataBinding.viewPager, tabTitles)
            }
        })

        viewModel.followResult.observe(this, {
            if (it.follow == userId) {
                doFollow(it.follow_related)
                GlobalMgr.follow.postValue(it)
            }
        })
    }

    private fun doFollow(related: Int) {
        when (related) {
            FOLLOW_UN -> {
                followBtnChange(R.drawable.ic_follow, R.string.follow_me, R.color.white)
                follow = FOLLOW_UN
            }
            FOLLOW_ALREADY -> {
                followBtnChange(
                    R.drawable.ic_alread_follow,
                    R.string.already_follow,
                    R.color.followTextColor
                )
                follow = FOLLOW_ALREADY
            }
            FOLLOW_EACH -> {
                followBtnChange(
                    R.drawable.ic_alread_follow,
                    R.string.follow_each_other,
                    R.color.followTextColor
                )
                follow = FOLLOW_ALREADY
            }
        }
    }

    override fun queryData() {
        viewModel.getUserInfo(userId)
        viewModel.getProductListInfo(userId)
    }

    private fun followBtnChange(@DrawableRes resId: Int, @StringRes text: Int, @ColorRes color:Int) {
        dataBinding.followBtn.background =
            context?.let { it1 -> ContextCompat.getDrawable(it1, resId) }
        dataBinding.followBtn.text = context?.getString(text)
        dataBinding.followBtn.setTextColor(ContextCompat.getColor(context!!, color))

        dataBinding.followUser.background =
            context?.let { it1 -> ContextCompat.getDrawable(it1, resId) }
        dataBinding.followUser.text = context?.getString(text)
        dataBinding.followUser.setTextColor(ContextCompat.getColor(context!!, color))
    }

    override fun getLayoutId(): Int = R.layout.fragment_detail_personal

    inner class AppbarLayoutChangeListener : AppBarLayout.OnOffsetChangedListener {
        override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
            val totalRange = dataBinding.appBarLayout.totalScrollRange
            val factor = abs(verticalOffset.toFloat()).div(totalRange)
            Log.e("factorValue", "verticalOffset ${verticalOffset}, factor : $factor")
            dataBinding.followUser.alpha = (1 - factor) * 255
            dataBinding.followBtn.alpha = factor * 255
            dataBinding.topIcon.alpha = factor * 255
            when (factor) {
                in 0.6..0.8 -> {
                    if (currentColor != Color.GRAY) {
                        dataBinding.personMsg.setColorFilter(Color.GRAY)
                        dataBinding.personShare.setColorFilter(Color.GRAY)
                        currentColor = Color.GRAY
                    }
                }
                in 0.8..0.9 -> {
                    if (currentColor != Color.DKGRAY) {
                        dataBinding.personMsg.setColorFilter(Color.DKGRAY)
                        dataBinding.personShare.setColorFilter(Color.DKGRAY)
                        currentColor = Color.DKGRAY
                    }
                }
                in 0.8..1.1 -> {
                    if (currentColor != Color.BLACK) {
                        dataBinding.personMsg.setColorFilter(Color.BLACK)
                        dataBinding.personShare.setColorFilter(Color.BLACK)
                        currentColor = Color.BLACK
                    }
                }
                else -> {
                    if (currentColor != Color.WHITE) {
                        dataBinding.personMsg.setColorFilter(Color.WHITE)
                        dataBinding.personShare.setColorFilter(Color.WHITE)
                        currentColor = Color.WHITE
                    }
                }
            }

            //头像动画修改
//            if (verticalOffset - verticalHeight > 0) {
//                val animFactor = abs(verticalOffset.div(verticalHeight))
//                translationView(animFactor)
//                Log.e("yanzhengoffset", "verticalOffset：${verticalOffset},  verticalHeight: ${verticalHeight}, animFactor: $animFactor")
//                Log.e("yanzhengoffset", "headAreaTOp:${dataBinding.headArea.top}, spaceBottom:${dataBinding.space.bottom} ", )
//            }

        }

    }

    private fun translationView(factor: Float) {
        val newAvatarSize = DensityUtils.dp2px(
            EXPAND_AVATAR_SIZE -
                    (EXPAND_AVATAR_SIZE - COLLAPSED_AVATAR_SIZE) * factor
        )
        val expandSize = DensityUtils.dp2px(EXPAND_AVATAR_SIZE)
        Log.e("yanzhengsize", "newAvatarSize:${newAvatarSize},  expandSize:$expandSize")
        val xAvatarOffset =
            (spacePoint[0] - avatarPoint[0] - (expandSize - newAvatarSize) / 2f) * factor
        val yAvatarOffset = (spacePoint[1] - avatarPoint[1] - (expandSize - newAvatarSize)) * factor
        dataBinding.headArea.layoutParams.width = round(newAvatarSize.toDouble()).toInt()
        dataBinding.headArea.layoutParams.height = round(newAvatarSize.toDouble()).toInt()
        Log.e("yanzhengoffset", "xAvatarOffset: ${xAvatarOffset}, spacePoint[0]: ${spacePoint[0]},avatarPoint[0]:${avatarPoint[0]}, expandSize: ${expandSize}, newAvatarSize: ${newAvatarSize}" )
        Log.e("yanzhengoffset", "yAvatarOffset: $yAvatarOffset, factor: ${factor}" )
        dataBinding.headArea.translationX = xAvatarOffset
        dataBinding.headArea.translationY = yAvatarOffset
    }

    private fun resetPoints() {

        val newAvatarSize = DensityUtils.dp2px(EXPAND_AVATAR_SIZE)
        val expandSize = DensityUtils.dp2px(EXPAND_AVATAR_SIZE)
        val pointAvatar  = IntArray(2)
        dataBinding.headArea.getLocationOnScreen(pointAvatar)
        avatarPoint[0] = pointAvatar[0] - dataBinding.headArea.translationY - (expandSize - newAvatarSize) / 2f
        avatarPoint[1] = pointAvatar[1] - dataBinding.headArea.translationY - (expandSize - newAvatarSize)

        val pointSpace = IntArray(2)
        dataBinding.topIcon.getLocationOnScreen(pointSpace)
        spacePoint[0] = pointSpace[0].toFloat()
        spacePoint[1] = pointSpace[1].toFloat()

        verticalHeight = avatarPoint[1] - spacePoint[1]
    }

    companion object {
        private const val EXPAND_AVATAR_SIZE = 80f
        private const val COLLAPSED_AVATAR_SIZE = 24f

        fun newInstance(): PersonalFragment  = PersonalFragment()
    }

    override fun getViewModuleClass(): Class<PersonalViewModel> {
        return PersonalViewModel::class.java
    }
}